package com.example.demo.start;

import java.io.*;

public class StudyJavaReaderIO {

    public static void main(String[] args) {
        try {
            reader("C:\\Users\\lzp\\Desktop\\test.sql");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 以字节的形式读取文件，指定编码读取
     * @param filePath 传入文件路径
     * @throws FileNotFoundException
     * @throws UnsupportedEncodingException
     */
    public static void reader(String filePath) throws IOException {
        File file = new File(filePath);
        FileInputStream fileInputStream = new FileInputStream(file);
        InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream,"UTF-8");
        StringBuffer stringBuffer = new StringBuffer();
        while (inputStreamReader.ready()){
            //System.out.println(inputStreamReader.read());
            stringBuffer.append((char) inputStreamReader.read());
        }
        System.out.println(String.valueOf(stringBuffer));
        fileInputStream.close();
        inputStreamReader.close();
    }

    /**
     * 不指定编码方式，字符流读取
     * @param filePath 传入文件路径
     * @throws IOException
     */
    public static void readerFile(String filePath) throws IOException {
        FileReader fileReader = new FileReader(filePath);
        System.out.println("返回的是文件流的字符编码" + fileReader.getEncoding());
        BufferedReader bufferedReader = new BufferedReader(fileReader);
        String line;
        while ((line = bufferedReader.readLine()) != null){
            System.out.println(String.valueOf(line));
        }
        bufferedReader.close();
        fileReader.close();
    }

    /**
     * 读取CMD窗口内容
     * @throws IOException 抛出异常信息
     */
    public static void readerCMD() throws IOException {
        // 使用 System.in 创建 BufferedReader
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String str;
        System.out.println("Enter lines of text.");
        System.out.println("Enter 'end' to quit.");
        do {
            str = br.readLine();
            System.out.println(str);
        } while (!str.equals("end"));
        br.close();
    }
}
